﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using SurvivalStrategy.WorldData;

namespace SurvivalStrategy
{
    //klasa zawierajaca informacje o swiecie
    public class World
    {
        public static int Width = 5;
        public static int Height = 5;

        public static Dictionary<int, ElementType> ElementsTypes = new Dictionary<int, ElementType>();

        private WorldChunk[,] worldChunks;
        public WorldChunk[,] Chunks { get { return worldChunks; } }

        private int elementsCount;
        public int ChunkCount { get { return elementsCount; } }

        public World()
        {
            Modules.BehaviorModule.SetWorld(this);
            Modules.ActionModule.SetWorld(this);
            PlayerController.SetWorld(this);

            elementsCount = 0;

            worldChunks = new WorldChunk[Width, Height];
            for (int i = 0; i < Width; i++)
                for (int j = 0; j < Height; j++)
                {
                    int id = i + j * Width;
                    worldChunks[i, j] = new WorldChunk(id, new Vector2(i, j));
                }
        }

        public static Vector2 WorldPositionToChunkPosition(Vector3 v)
        {
            return new Vector2((int)(v.X / WorldChunk.Width), (int)(v.Z / WorldChunk.Height));
        }

        public WorldChunk GetPositionsChunk(Vector3 v)
        {
            if(v.X >= 0 && v.Z >= 0)    
                return worldChunks[(int)(v.X / WorldChunk.Width), (int)(v.Z / WorldChunk.Height)];
            return null;
        }

        public List<WorldElement> GetPositionsElements(Vector3 v)
        {
            return GetPositionsChunk(v).GetWorldElements(v);
        }

        public void Update()
        {
            TestChunkData();
        }

        public void AddElement(WorldElement element)
        {
           // this.GetPositionsElements(element.Position).Add(element);
            element.SetElementId(elementsCount);
            this.GetPositionsChunk(element.Position).AddElement(element);
            elementsCount++;
        }

        private void TestChunkData()
        {
            ///TEST RYSUJE TE POLA W CHUNKDATA KTORE MAJA CHOCIAZ JEDEN ELEMENT PRZYPISANY DO NICH
            foreach (WorldChunk c in worldChunks)
                for (int i = 0; i < c.ChunkData.GetLength(0); i++)
                    for (int j = 0; j < c.ChunkData.GetLength(1); j++)
                        if (c.ChunkData[i, j].Count > 0)
                            View.DrawDebugImage(new Vector2(c.position.X * WorldChunk.Width + i * WorldChunk.CellWidth, c.position.Y * WorldChunk.Height + j * WorldChunk.CellHeight), 0);
        }
    }
}
